package com.liang.subject.domain.service.impl;

import com.liang.subject.common.enums.CategoryTypeEnum;
import com.liang.subject.domain.convert.SubjectLabelConverter;
import com.liang.subject.domain.entity.SubjectLabelBO;
import com.liang.subject.domain.service.SubjectLabelDomainService;
import com.liang.subject.infra.basic.entity.SubjectCategory;
import com.liang.subject.infra.basic.entity.SubjectLabel;
import com.liang.subject.infra.basic.service.SubjectCategoryService;
import com.liang.subject.infra.basic.service.SubjectLabelService;
import com.liang.subject.infra.basic.service.SubjectMappingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SubjectLabelDomainServiceImpl implements SubjectLabelDomainService {

    private final SubjectLabelService subjectLabelService;
    private final SubjectCategoryService subjectCategoryService;
    private final SubjectMappingService subjectMappingService;

    @Override
    public Boolean add(SubjectLabelBO subjectLabelBO) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.convertBoToEntity(subjectLabelBO);
        return subjectLabelService.save(subjectLabel);
    }

    @Override
    public Boolean update(SubjectLabelBO subjectLabelBO) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.convertBoToEntity(subjectLabelBO);
        return subjectLabelService.updateById(subjectLabel);
    }

    @Override
    public void delete(SubjectLabelBO subjectLabelBO) {
        SubjectLabel subjectLabel = SubjectLabelConverter.INSTANCE.convertBoToEntity(subjectLabelBO);
        subjectLabelService.removeById(subjectLabel.getId());
    }

    @Override
    public List<SubjectLabelBO> queryLabelByCategory(SubjectLabelBO subjectLabelBO) {
        // 如果是一级分类，则直接返回所有标签
        SubjectCategory subjectCategory = subjectCategoryService.getById(subjectLabelBO.getCategoryId());
        Integer categoryType = subjectCategory.getCategoryType();
        if (CategoryTypeEnum.PRIMARY.getCode() == categoryType) {
            List<SubjectLabel> subjectLabelList = subjectLabelService.queryByCategoryType(categoryType);
            return SubjectLabelConverter.INSTANCE.convertToBoList(subjectLabelList);
        }
        Long categoryId = subjectLabelBO.getCategoryId();
        List<SubjectLabel> labelList = subjectMappingService.getLabelListByCategoryId(categoryId);
        List<SubjectLabelBO> subjectLabelBOList = SubjectLabelConverter.INSTANCE.convertToBoList(labelList);
        subjectLabelBOList.forEach(item -> item.setCategoryId(categoryId));
        return subjectLabelBOList;
    }
}
